/*
 * @Author: 江舟 jijiangzhou@recycloud.cn
 * @Date: 2024-05-28 16:02:46
 * @LastEditors: 江舟 jijiangzhou@recycloud.cn
 * @LastEditTime: 2024-08-06 15:27:36
 * @FilePath: \vite-project\src\components\common\PictureCode.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { sendPicCaptcha } from 'apis/common';
import { Icon } from '@iconify/react/dist/iconify.js';
import { Image, Input, Spin, Tooltip } from 'antd';
import React, { useEffect, useState } from 'react';
import { LoadingOutlined } from '@ant-design/icons';

const PictureCode: React.FC<{
    value?: {};
    refreshTime?: number;
    onChange?: (data: { picKey?: string; picCaptcha?: string }) => void;
}> = ({ onChange, refreshTime }) => {
    const [loading, setLoading] = useState(false);
    const [result, setResult] = useState<{
        picKey?: string;
        picBase64?: string;
    }>({
        picBase64: void 0,
        picKey: void 0,
    });

    const onRefresh = () => {
        if (loading) {
            return;
        }
        setLoading(true);
        sendPicCaptcha({})
            .then((res) => {
                setResult(res);
            })
            .catch(() => {})
            .finally(() => {
                setLoading(false);
            });
    };

    useEffect(() => {
        onRefresh();
    }, [refreshTime]);
    return (
        <div className='flex space-x-12px'>
            <Input
                size='large'
                prefix={<Icon className='text-20px' icon='icon-park-twotone:key-one' />}
                placeholder='请输入验证码'
                onChange={(e) => {
                    onChange?.({
                        picKey: result?.picKey,
                        picCaptcha: e.target.value,
                    });
                }}
            />

            <Tooltip placement='top' title='点击刷新验证码'>
                <Spin spinning={loading} indicator={<LoadingOutlined />}>
                    {result.picBase64 ? (
                        <Image
                            onClick={onRefresh}
                            className='border-[#d9d9d9] border-1px border-solid rounded-8px'
                            preview={false}
                            alt='验证码'
                            height={40}
                            src={`data:image/ico;base64,${result.picBase64}`}
                        />
                    ) : (
                        <div
                            onClick={onRefresh}
                            className='border-[#d9d9d9] border-1px border-solid rounded-8px text-center px-8px whitespace-nowrap h-40px leading-40px'
                        >
                            获取失败
                        </div>
                    )}
                </Spin>
            </Tooltip>
        </div>
    );
};

export default PictureCode;
